/*
 * @Author: Hp_lucky 1063512385@qq.com
 * @Date: 2024-08-30 10:10:26
 * @LastEditors: Hp_lucky 1063512385@qq.com
 * @LastEditTime: 2024-09-30 10:41:27
 * @FilePath: \cocos_frame\assets\script\src\Util\SpineUitl.ts
 */
/* eslint-disable */
import { sp, SpriteFrame, Texture2D } from 'cc';
import { LogUtil } from './LogUtil';

export module SpineUtil {
  export function changeSkeletonSlots(ani: sp.Skeleton, slotName: string, sprite: SpriteFrame) {
    const slot: sp.spine.Slot = ani.findSlot(slotName);
    if (!slot) {
      LogUtil.w('找不到插槽: ' + slotName);
      return;
    }
    const skeletonData = ani.skeletonData.getRuntimeData() as sp.spine.SkeletonData;
    const skin = skeletonData.findSkin('bone/bone_weapon');
    let skinEntry: sp.spine.SkinEntry;
    const attachments = skin.getAttachments();
    for (let i = 0; i < attachments.length; i++) {
      if (attachments[i].name == 'skin/w_k_1') {
        skinEntry = attachments[i];
        break;
      }
    }
    const attachment: sp.spine.RegionAttachment = skinEntry.attachment as sp.spine.RegionAttachment;
    const tex2d = sprite.texture; //替换需要的textrue，注意如果用了自动合批，会导致把合批的图弄进来
    const region = this.createRegion(tex2d);
    //@ts-ignore
    let skeletonTexture = new sp.SkeletonTexture({ width: tex2d.width, height: tex2d.height } as ImageBitmap);
    if (tex2d) {
      skeletonTexture.setRealTexture(tex2d);
    }
    region.texture = skeletonTexture;
    //@ts-ignore
    attachment.setRegion(region);
    attachment.width = region.width;
    attachment.height = region.height;
    attachment.updateOffset();
    ani.invalidAnimationCache();
  }

  export function createRegion(tex2d: Texture2D): sp.spine.TextureAtlasRegion {
    //@ts-ignore
    let skeletonTexture = new sp.spine.SkeletonTexture({ width: tex2d.width, height: tex2d.height } as ImageBitmap);
    if (tex2d) {
      skeletonTexture.setRealTexture(tex2d);
    }

    let region = new sp.spine.TextureAtlasRegion();
    region.width = tex2d.width;
    region.height = tex2d.height;
    region.originalWidth = tex2d.width;
    region.originalHeight = tex2d.height;
    region.rotate = false;
    region.u = 0;
    region.v = 0;
    region.u2 = 1;
    region.v2 = 1;
    region.texture = skeletonTexture;
    return region;
  }
}
